/*
 * $RCSfile: Bootstrap.java,v $
 * $Revision: 1.1 $
 * $Date: 2009-11-02 $
 *
 * Copyright (C) 2008 Skin, Inc. All rights reserved.
 *
 * This software is the proprietary information of Skin, Inc.
 * Use is subject to license terms.
 */
package com.skin.startup;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Title: Bootstrap</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2006</p>
 * @author xuesong.net
 * @version 1.0
 */
public class Bootstrap {
    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("Bootstrap.start...");
        String className = getClassName(args);

        if(className == null) {
            usage();
            return;
        }

        String[] arguments = slice(args, 1, args.length - 1);

        try {
            List<URL> repositories = new ArrayList<URL>();
            BootstrapClassLoader.addRepositories(repositories, new File("lib").listFiles());
            repositories.add(new File("classes").toURI().toURL());

            ClassLoader parent = Thread.currentThread().getContextClassLoader();
            ClassLoader classLoader = BootstrapClassLoader.getClassLoader(parent, repositories);
            Class<?> clazz = classLoader.loadClass(className);
            Thread.currentThread().setContextClassLoader(classLoader);
            Method method = clazz.getMethod("main", new Class[]{String[].class});
            method.invoke(null, new Object[]{arguments});
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param args
     * @param start
     * @param end
     * @return result
     */
    public static String[] slice(String[] args, int start, int end) {
        int s = start;
        int e = end;
        
        if(s < 0) {
            s = args.length + s;
        }
        
        if(e < 0) {
            e = args.length + e;
        }

        String[] result = new String[e - s + 1];

        for(int i = 0; i < result.length; i++) {
            result[i] = args[s + i];
        }
        return result;
    }
    
    /**
     * @param args
     * @return String
     */
    private static String getClassName(String[] args) {
        if(args == null || args.length < 1) {
            return null;
        }

        String className = args[0];
        
        if(className != null) {
            className = className.trim();
        }

        if(className != null && className.length() > 0) {
            return className;
        }
        return null;
    }

    /**
     * 
     */
    public static void usage() {
        System.out.println(Bootstrap.class.getName() + " CLASS_NAME [arg0[, arg1...]]");
    }
}
